package com.woniuxy.background.realm;

import com.woniuxy.background.dao.AdminMapper;
import com.woniuxy.background.dao.MenuMapper;
import com.woniuxy.background.pojo.Admin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private MenuMapper menusMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin admin = adminMapper.findByName(principalCollection.getPrimaryPrincipal().toString());
        //查询权限数据
        List<String> perms = menusMapper.selectPermsByRoleId(admin.getRoleId());
        System.out.println(perms);
        perms = perms.stream().filter(s-> s!= null && !s.isEmpty()).collect(Collectors.toList());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);
        System.out.println("权限："+perms);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = token.getPrincipal().toString();
        Admin admin = adminMapper.findByName(userName);
        if(admin == null){
            throw new UnknownAccountException("账号不存在");
        }
        System.out.println(admin);
        //比较密码
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),super.getName());
        return info;



       }
}
